class Book < ActiveRecord::Base

  validates :isbn, :name, presence: true
  validates_uniqueness_of :isbn

  belongs_to :category
  has_one :attachment
  has_many :transactions, dependent: :destroy

  acts_as_commentable
  ajaxful_rateable :stars => 10, :dimensions => [:quality]
  mount_uploader :image, ImageUploader

  attr_accessible :amazon_link, :author, :category_id, 
    :copies, :description, :isbn, :publish_date, :publisher, 
    :total_rate, :name, :image, :remote_image_url

  searchable do
    string :description
    string :name
    string :author
    string :publisher
    string :isbn
    integer :category_id
  end

  def is_rated_by?(user)
    rate = self.rates.find_by_rater_id(user.id)
    rate.present?
  end

  def self.search_by(keyword, page, column, direction)
    column ||= :score
    direction ||= :desc
    Book.search do
      fulltext keyword
      paginate page: page, per_page: 20
      order_by column, direction
    end.results
  end
end
